<!-- 话费充值 -->
<template>
    <div class="telephoneCharge">
        <van-nav-bar title="抖币充值" right-text="查询记录" @click-right="onClickRight" left-arrow :border="false" @click-left="onClickLeft"/>
        <div class="head">
            <div class="flex alignCenter">
                <div class="headLabel">充值账号</div>
                <div class="headRight allFlex">
                    <van-field input-align="right" v-model="phone" placeholder="请输入充值账号" />
                </div>
            </div>
            <!-- <div class="flex alignCenter">
                <div class="headLabel">标签</div>
                <div style="padding-left: 70px" class="headRight allFlex flex alignCenter justifyAround">
                    <div @click="selInvoiceType(item)" :class="`electricType ${item.id == invoiceType ? 'active' : ''}`" v-for="item in invoiceTypeList" :key="item.id">{{item.name}}</div>
                </div>
            </div> -->
        </div>
        <!-- 产品模块展示 -->
        <div class="content flex justifyBetween" v-if="productList.length > 0">
            <div @click="selProduct(item)" class="productItem flex flexColumn alignCenter justifyCenter" v-for="item in productList" :key="item.id">
                <div class="facePrice"><span>{{item.facePrice}}</span>元</div>
                <div>售价{{item.price}}元</div>
            </div>
        </div>
        <div v-else class="content  flex justifyBetween alignCenter">
            <div>暂无充值面额</div>
        </div>
        <!-- 充值渠道 -->
        <div class="channel">
            <div @click="changeChannel(item)" class="channelItem flex alignCenter justifyBetween" v-for="item in channelList" :key="item.id">
                <div class="flex alignCenter"><img :src="item.icon" alt="">{{item.name}}</div>
                <img v-if="item.id == activeChannel" class="activeIcon" src="@/assets/lifePayCost/activeIcon.png" alt="">
                <img v-else src="@/assets/lifePayCost/unActiveIcon.png" alt="">
            </div>
        </div>
        <!-- 充值须知 -->
        <div class="desc">
            <div class="descHead flex alignCenter"><span />充值须知</div>
            <div class="descItem">
                1.快充低价一般为1小时内到账，特殊情况会延迟到账，但一般不超过2小时。
            </div>
            <div class="descItem">
                2.慢充低价日常48小时内到账，高峰期72小时内到账，个别到账时间可能延至96小时，超时未到账全额退款，不支持催单，急用勿拍。
            </div>
            <div class="descItem">
                3.下单后系统自动提交充值，人工无法干预退款或更改号码，请您仔细核对充值号码，空号充值成功无法撤回，充错号码概不负责。
            </div>
            <div class="descItem">
                4.因运营商资源、系统接口等问题，可能导致个别订单充值失败，充值失败系统会自动全额退款，若失败订单没有及时返回等情况，请主动联系客服。
            </div>
            <div class="descItem">
                5.本平台不提供发票，如需发票请前往营业厅或官方APP开取。
            </div>
        </div>

        <!-- 客服 -->
        <lifePayCostService></lifePayCostService>
    </div>
</template>

<script>
import { ref, reactive, getCurrentInstance } from 'vue';
import storage from 'store';
import { Field , CellGroup , NavBar } from 'vant';
import { getOperator , getUserAgent } from '@/utils';
import { userAgent } from '@/utils/types';
import { ACCESS_TOKEN , BRANDID , ACCESS_TOKEN_BRAND } from '@/utils/types';
import { dataEncryption , delNoneParameter } from '@/utils';
import qs from 'qs'
import lifePayCostService from '@/components/lifePayCostService';
export default {
    components: {
        [Field.name]: Field,
        [CellGroup.name]: CellGroup,
        [NavBar.name]: NavBar,
        lifePayCostService,
    },
    setup() {
        const { proxy } = getCurrentInstance();
        console.log(proxy.$route.params)
        const appId = storage.get('appId')
        // 返回上一页
        const onClickLeft = () => history.back();
        // 跳转查询记录
        const onClickRight = () => proxy.$router.push({name: 'lifePayCostBillBefore',params: {'orderType': 4}});

        const getConfig = () =>{
            let url = window.location.href.split('#')[0]
            // var url = 'https://szk.lexiangaysh.cn/'
            proxy.$http.externalApi.queryWxConfig(url,storage.get(BRANDID))
            .then(res=>{
                if(res.success){
                    wx.config({
                        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                        appId: appId, // 必填，公众号的唯一标识
                        timestamp: Number(res.data.timestamp), // 必填，生成签名的时间戳
                        nonceStr: res.data.nonceStr, // 必填，生成签名的随机串
                        signature: res.data.signature,// 必填，签名
                        jsApiList: ['updateAppMessageShareData','chooseWXPay'], // 必填，需要使用的JS接口列表
                    })
                }
            })
        }
        // 用户终端
        const userAgents = getUserAgent()
        if(userAgents == userAgent.WECHAT){
            getConfig();
        }

        console.log(userAgents,'userAgent')
        // 商户号
        const merchantNo = storage.get('merchantNo');
        // 版本信息
        const edition = proxy.$route.params.edition;
        // 运营商（默认）
        const operator = ref('0');
        // 充值账号
        const phone = ref('');
        // 发票类型
        const invoiceType = ref('3');
        const invoiceTypeList = [
            { 'id': '1', 'name': '专票'},
            { 'id': '2', 'name': '普票'},
            { 'id': '3', 'name': '无票'},
        ];
        // 选择发票类型
        const selInvoiceType = (item) =>{
            invoiceType.value = item.id
            getProduct();
        }

        // 获取充值产品
        const productList = ref([]);
        const getProduct = () =>{
            proxy.$http.externalApi.queryExternalRechargeProduct({merchantNo: merchantNo,edition: edition,operator: operator.value,classificationId: 4,invoice: invoiceType.value})
            .then(res=>{
                if(res.success){
                    productList.value = res.data;
                }else{
                    proxy.$toast({position: 'bottom',message:res.errMessage})
                }
            })
        }
        getProduct();

        // 选择充值渠道
        const activeChannel = ref(2);
        const channelList = [
            { 'id': 1, 'name': '支付宝', 'icon': require('../../assets/lifePayCost/zhfbIcon.png')},
            { 'id': 2, 'name': '微信', 'icon': require('../../assets/lifePayCost/wxIcon.png')},
        ];
        const changeChannel = (item) =>{
            activeChannel.value = item.id;
        }

        const confirmProduct = (item) =>{
            proxy.$http.externalApi.tiktokCurrencyRechargePlaceOrder({merchantNo: merchantNo,rechargeType: edition,account: phone.value,facePrice: item.facePrice,invoiceType: invoiceType.value})
            .then(async res=>{
                if(res.success){
                    if(userAgents == userAgent.WECHAT){
                        if(activeChannel.value == 2){
                            var openId = await getOpenId();
                            pay(res.data,{openId: openId})
                        }else{
                            const params = {
                                'merchantNo': merchantNo,
                                'orderCode': res.data,
                                'payType': activeChannel.value,
                            }
                            const objPar = delNoneParameter(Object.assign(qs.parse(qs.stringify(params)),dataEncryption(qs.parse(qs.stringify(params)))))
                            let paramsArr = new Array()
                            // console.log(dataObj)
                            Object.keys(objPar).sort().map(function(key){
                                // 判断key值的类型，文件的过滤掉
                                if(typeof(objPar[key]) != 'object'  && objPar[key] !== "" && objPar[key] != undefined){
                                    paramsArr.push(
                                    key + '=' + objPar[key]
                                    )
                                }
                            })
                            let paramsStr = paramsArr.join('&')
                            var url = `https://${window.location.host}${process.env.VUE_APP_API_BASE_URL}/open/api/promotion/recharge/pay?${paramsStr}`;
                            proxy.$router.push({name: 'gathering', params: {'title': '支付宝支付','money': item.price, 'url': url}})
                        }
                    }else{
                        pay(res.data,{openid: undefined})
                    }
                }else{
                    proxy.$toast({position: 'bottom',message:res.errMessage})
                }
            })
        }

        // 选择充值产品
        const selProduct = (item) =>{
            console.log(item.edition,'item')
            if(phone.value == ''){
                proxy.$toast({message: '请输入正确的充值账号！',position: 'bottom'})
                return;
            }
            // 如果是在微信，无法使用支付宝，否则无法使用微信支付
            // if(userAgents == userAgent.WECHAT && activeChannel.value == 1){
            //     proxy.$toast({message: '微信内无法使用支付宝支付，请更换支付方式',position: 'bottom'})
            //     return;
            // }
            if(userAgents !== userAgent.WECHAT && activeChannel.value == 2){
                proxy.$toast({message: '微信支付必须要在微信浏览器内支付，请更换其他支付方式',position: 'bottom'})
                return;
            }
            proxy.$dialog.confirm({
                title: '温馨提示',
                message: `请确认充值账号：${phone.value} ，充值金额 ${item.facePrice} 元？`,
            }).then(()=>{confirmProduct(item);})
            
        }
        // 支付
        const pay = (orderCode,{openId = ''}) =>{
            proxy.$http.externalApi.promotionRechargePay({merchantNo: merchantNo,orderCode: orderCode,payType: activeChannel.value,openId: openId})
            .then(res=>{
                if(userAgents != userAgent.WECHAT){
                    var div = document.createElement('div')
                    div.innerHTML = res
                    document.body.appendChild(div)
                    document.forms[0].submit()
                }else{
                    if(res.success){
                    // 微信下需要掉起微信支付，微信外处理支付宝返回数据
                    if(userAgents == userAgent.WECHAT){
                        var resData = JSON.parse(res.data)
                        console.log(resData,'resData')
                        wx.chooseWXPay({
                            timestamp: resData.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
                            nonceStr: resData.nonceStr, // 支付签名随机串，不长于 32 位
                            package: resData.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
                            signType: resData.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
                            paySign: resData.paySign, // 支付签名
                            appId: resData.appId,
                            success: function (res) {
                                // 支付成功后的回调函数
                                proxy.$toast({message: '支付成功',position: 'bottom'})
                            },
                        });
                    }else{
                        
                    }
                }else{
                    proxy.$toast({position: 'bottom',message:res.errMessage})
                }
                }
            })
        }
        // 微信支付需要获取用户的OpenId
        const getOpenId = () =>{
            return new Promise((resolve,reject) =>{
                proxy.$http.externalApi.queryWxOpenId({code: storage.get('code'),brandId: storage.get(BRANDID)})
                .then(res=>{
                    if(res.success){
                        resolve(res.data.openid)
                    }else{
                        proxy.$toast({position: 'bottom',message:res.errMessage})
                    }
                })
            })
        }

        return {
            onClickLeft,
            onClickRight,
            productList,
            operator,
            phone,
            channelList,
            activeChannel,
            changeChannel,
            selProduct,
            invoiceType,
            invoiceTypeList,
            selInvoiceType,
        }
    }
}

</script>
<style scoped>
.telephoneCharge{
    min-height: 100vh;
    background: url('../../assets/lifePayCost/telPhoneChargeHeadBg.png') no-repeat;
    background-size: 100%;
}
.telephoneCharge /deep/ .van-cell-group__title{
    font-size: 14px;
    color: #FFFFFF;
}
.telephoneCharge /deep/ .van-cell,.telephoneCharge /deep/ .van-cell-group,.telephoneCharge /deep/ .van-hairline--top-bottom{
    background: none;
    border: none;
    position: inherit;
}
.telephoneCharge /deep/ .van-field__control{
    font-size: 20px;
    /* color: #FFFFFF; */
}
.phoneHome{
    padding-left: 20px;
    color: #FFFFFF;
    font-size: 14px;
}
.telephoneCharge /deep/ .van-nav-bar{
    background: none;
}
.telephoneCharge /deep/ .van-icon{
    color: #FFFFFF;
}
.telephoneCharge /deep/ .van-nav-bar__title{
    color: #FFFFFF;
}
.telephoneCharge /deep/ .van-nav-bar__text{
    color: #FFFFFF;
}

/* 头部输入内容 */
.head{
    margin: 0 12px 10px;
    border-radius: 8px;
    background: #FFFFFF;
    padding: 10px 10px;
}
.head>div{
    height: 55px;
}
.headLabel{
    font-size: 15px;
    color: #333333;
}
.headLabel::after{
    content: '*';
    color: red;
}
.headRight span{
    font-size: 15px;
    color: #ACACAC;
}
.electricType{
    width: 51px;
    height: 25px;
    border-radius: 13px;
    text-align: center;
    color: #666666;
    font-size: 15px;
    line-height: 25px;
    background: #DFEEFF;
}
.electricType.active{
    color: #FFFFFF;
    background: var(--themeColor);
}

/* 产品模块展示 */
.content{
    margin: 10px 12px;
    border-radius: 8px;
    background: #FFFFFF;
    flex-wrap: wrap;
    padding: 22px 10px;
}
.productItem{
    width: 105px;
    height: 72px;
    background: #F7FBFF;
    border-radius: 5px;
    font-size: 12px;
    color: #888888;
}
.facePrice{
    font-size: 15px;
    color: var(--themeColor);
}
.facePrice span{
    font-size: 25px;
    font-weight: bold;
}
/* 充值渠道 */
.channel,.desc{
    margin: 10px 12px;
    border-radius: 8px;
    background: #FFFFFF;
    padding: 10px 20px;
}
.channelItem{
    height: 45px;
    font-size: 15px;
    color: #333333;
}
.channelItem img{
    width: 18px;
    height: 18px;
    margin-right: 10px;
    display: inline-block;
}
/* 充值须知 */
.descHead{
    font-size: 15px;
    font-weight: 500;
    color: #333333;
}
.descHead span{
    height: 14px;
    width: 3px;
    background: linear-gradient(to top, #2184F8 , #FFFFFF);
    margin-right: 10px;
}
.descItem{
    font-size: 13px;
    color: #666666;
    margin: 5px 0;
}
</style>